package com.gt.xmall.security;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.Ini.Section;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.gt.xmall.model.SysResource;
import com.gt.xmall.service.SysResourceService;

public class ChainDefinitionSectionMetaSource implements FactoryBean<Section> {

	private String filterChainDefinitions;

	@Autowired
	SysResourceService sysResourceService;
	/**
	 * 默认premission字符串
	 */
	public static final String PREMISSION_STRING = "perms[\"{0}\"]";

	@Override
	public Section getObject() throws Exception {
		// TODO Auto-generated method stub
		// 获取所有Resource
		List<SysResource> list = sysResourceService.getAllSysResource();

		Ini ini = new Ini();
		// 加载默认的url
		ini.load(filterChainDefinitions);
		Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
		// 循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap,
		// 里面的键就是链接URL,值就是存在什么条件才能访问该链接
		for (Iterator it = list.iterator(); it.hasNext();) {

			SysResource resource = (SysResource) it.next();
			// 如果不为空值添加到section中
			if (StringUtils.isNotEmpty(resource.getResUrl())
					&& !CollectionUtils.isEmpty(resource.getSysRoles())) {
				section.put(
						resource.getResUrl(),
						MessageFormat.format(PREMISSION_STRING,
								resource.getPermission()));
			}

		}

		return section;
	}

	@Override
	public Class<?> getObjectType() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isSingleton() {
		// TODO Auto-generated method stub
		return false;
	}

}
